package com.ocom.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @description: 根据文件链接地址下载文件
 * @author: zyb
 * @date: 2020/10/13 15:47
 */
@Slf4j
public class DownloadFileUtils {
    public static void main(String[] args) {
        downloadA("文件链接地址", "下载存放地址 + 文件名+后缀");
        downloadB("文件链接地址", "文件名+后缀", "下载存放地址");
    }



    /**
     *
     * @param urlPath     下载路径
     * @param fileSavePath 下载存放目录,包含文件名
     * @return 返回下载文件
     * @throws Exception
     */
    public static File downloadFile(String urlPath, String fileSavePath) throws Exception {

        log.info("进入下载文件工具类");
        File file = null;
        BufferedInputStream bin = null;
        OutputStream out = null;
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            // 设定请求的方法，默认是GET
            httpURLConnection.setRequestMethod("GET");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL 引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();

            // 文件大小
            int fileLength = httpURLConnection.getContentLength();

            // 文件名
            String filePathUrl = httpURLConnection.getURL().getFile();
            String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
            fileFullName = fileFullName.substring(fileFullName.lastIndexOf("/") + 1);
            log.info("开始下载文件：" + fileFullName);
            log.info("file length---->" + fileLength);

            url.openConnection();

            bin = new BufferedInputStream(httpURLConnection.getInputStream());

            String path = fileSavePath;
            file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            out = new FileOutputStream(file);
            int size = 0;
            int len = 0;
            byte[] buf = new byte[1024];
            while ((size = bin.read(buf)) != -1) {
                len += size;
                out.write(buf, 0, size);
                // 打印下载百分比
                if ((len * 100 / fileLength)>50&&(len * 100 / fileLength)<55) {
//                    log.info("下载了-------> " + len * 100 / fileLength + "%");
                }else    if ((len * 100 / fileLength)>=98) {
//                    log.info("下载了-------> " + len * 100 / fileLength + "%");
                }
                //log.info("下载了-------> " + len * 100 / fileLength + "%");
            }
            return file;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            return null;
        } finally {
            if (bin!=null) {
                bin.close();
            }
            if (out!=null) {
                out.close();
            }
        }
    }


    /**
     * 根据链接地址下载文件
     * @param downloadUrl 文件链接地址
     * @param path        下载存放文件地址 + 文件名
     */
    public static boolean downloadA(String downloadUrl, String path) {
        URL url = null;
        DataInputStream dataInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            url = new URL(downloadUrl);
            dataInputStream = new DataInputStream(url.openStream());
            fileOutputStream = new FileOutputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (dataInputStream != null){
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }
    /**
     * @param downloadUrl 文件链接地址
     * @param filename    保存文件名
     * @param filePath    保存文件路径
     */
    public static void downloadB(String downloadUrl, String filename, String filePath) {
        URL url = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            url = new URL(downloadUrl);
            // 打开连接
            URLConnection con = url.openConnection();
            // 请求超时:5s
            con.setConnectTimeout(5 * 1000);
            inputStream = con.getInputStream();

            byte[] bytes = new byte[1024];
            // 读取到的数据长度
            int length;
            File savePath = new File(filePath);
            if (!savePath.exists()) {
                // 如果不存在当前文件夹，则创建该文件夹
                boolean mkdir = savePath.mkdirs();
                if (!mkdir) {
                    System.out.println("创建文件夹失败");
                    return;
                }
            }
            outputStream = new FileOutputStream(savePath.getPath() + "\\" + filename);
            // 读取
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}